package com.hontech.libratest.utils

import com.hontech.libratest.conn.DeviceConst


interface SerialType {

    fun decode(buf: ByteArray, index: Int)

    fun encode(buf: ByteArray, index: Int)

    fun size(): Int
}

class UInt8(var value: Int = 0) : SerialType {

    override fun decode(buf: ByteArray, index: Int) {
        value = buf.toUInt8(index)
    }

    override fun size(): Int {
        return 1
    }

    override fun encode(buf: ByteArray, index: Int) {
        buf.encodeUInt8(index, value)
    }

    fun isOk() = (value == 0x00)

    fun signedValue(): Int {
        if ((value and 0x80) == 0) {
            return value
        }
        return -(0x100 - value)
    }

    fun errMsg(): String {
        return DeviceConst.msgWithCode(value)
    }
}

class UInt16(var value: Int = 0) : SerialType {

    override fun decode(buf: ByteArray, index: Int) {
        value = buf.toUInt16(index)
    }

    override fun size(): Int {
        return 2
    }

    override fun encode(buf: ByteArray, index: Int) {
        buf.encodeUInt16(index, value)
    }

    fun signedValue(): Int {
        if ((value and 0x8000) == 0) {
            return value
        }
        return -(0x10000 - value)
    }
}

class UInt32(var value: Int = 0) : SerialType {

    override fun decode(buf: ByteArray, index: Int) {
        value = buf.toUInt32(index)
    }

    override fun size(): Int {
        return 4
    }

    override fun encode(buf: ByteArray, index: Int) {
        buf.encodeUInt32(index, value)
    }
}

class ByteView(
    var buf: ByteArray = byteArrayOf(),
    var index: Int = 0,
    var size: Int = buf.size - index
) : SerialType {

    override fun decode(buf: ByteArray, index: Int) {
        val len = buf.toUInt16(index)
        this.buf = buf
        this.index = index + 2
        this.size = len
    }

    override fun size(): Int {
        return 2 + size
    }

    override fun encode(buf: ByteArray, index: Int) {
        buf.encodeUInt16(index, size)
        System.arraycopy(this.buf, this.index, buf, index + 2, this.size)
    }

    override fun toString(): String {
        return String(buf, index, size, Charsets.UTF_8)
    }
}


